package net.fornwall.eclipsecoder.haskell;

import java.io.ByteArrayInputStream;

import net.fornwall.eclipsecoder.languages.LanguageSupport;
import net.fornwall.eclipsecoder.stats.CodeGenerator;
import net.fornwall.eclipsecoder.stats.ProblemStatement;
import net.fornwall.eclipsecoder.util.Utilities;
import net.sf.eclipsefp.haskell.core.HaskellCorePlugin;
import net.sf.eclipsefp.haskell.core.preferences.ICorePreferenceNames;
import net.sf.eclipsefp.haskell.core.project.HaskellProjectCreationOperation;
import net.sf.eclipsefp.haskell.ui.HaskellUIPlugin;
import net.sf.eclipsefp.haskell.ui.editor.HaskellEditor;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.runtime.NullProgressMonitor;

public class HaskellLanguageSupport extends LanguageSupport {

    @Override
    protected CodeGenerator createCodeGenerator(ProblemStatement problemStatement) {
        return new HaskellCodeGenerator(problemStatement);
    }

    private IFile sourceFile;

    @Override
    protected IFile createLanguageProject(IProject project) throws Exception {
        HaskellProjectCreationOperation creationOperation = new HaskellProjectCreationOperation();
        creationOperation.setProjectName(project.getName());
        creationOperation.run(new NullProgressMonitor());

        // we trust in that the HaskellProjectCreationOperation has created this folder
        String srcFolder = HaskellCorePlugin.getDefault().getPluginPreferences().getString(
                ICorePreferenceNames.FOLDERS_SRC);

        sourceFile = project.getFile(project.getProjectRelativePath().append(srcFolder).append(
                getProblemStatement().getSolutionClassName() + ".hs"));
        sourceFile.create(new ByteArrayInputStream(getInitialSource().getBytes()), false, null);

        IFile testsFile = project.getFile(project.getProjectRelativePath().append(srcFolder)
                .append(getProblemStatement().getSolutionClassName() + "Test.hs"));
        testsFile.create(new ByteArrayInputStream(getCodeGenerator().getTestsSource().getBytes()),
                false, null);

        return sourceFile;
    }

    @Override
    protected String getCodeEditorID() {
        return HaskellEditor.ID;
    }

    @Override
    protected String getCodeTemplate() {
        // TODO: add type signature declaration
        return "module " + CLASSNAME_TAG + " where \n\n" + METHODNAME_TAG + " " + METHODPARAMS_TAG
                + " = " + DUMMYRETURN_TAG + "\n";
    }

    @Override
    public String getLanguageName() {
        return "Haskell";
    }

    @Override
    public String getPerspectiveID() {
        return HaskellUIPlugin.ID_PERSPECTIVE;
    }

    @Override
    protected String getSolutionFileName() {
        return getProblemStatement().getClassName() + ".hs";
    }

    @Override
    protected String getSubmission() throws Exception {
        return Utilities.getFileContents(sourceFile);
    }

}
